#include "simple_property_editor.h"
#include <wx/sizer.h>
#include <wx/tokenzr.h>

wxBEGIN_EVENT_TABLE(SimplePropertyEditor, wxPanel)
    EVT_TREE_SEL_CHANGED(wxID_ANY, SimplePropertyEditor::OnTreeSelectionChanged)
    EVT_PG_CHANGED(wxID_ANY, SimplePropertyEditor::OnPropertyChanged)
    EVT_STC_MODIFIED(wxID_ANY, SimplePropertyEditor::OnEditorModified)
wxEND_EVENT_TABLE()

SimplePropertyEditor::SimplePropertyEditor(wxWindow* parent)
    : wxPanel(parent, wxID_ANY)
{
    CreateControls();
    SetupPropertyLexer();
    
    // 设置示例内容
    wxString exampleContent = 
        "# 示例属性文件\n"
        "[Compiler]\n"
        "name = gcc\n"
        "optimization = 2\n"
        "debug = true\n"
        "\n"
        "[Linker]\n"
        "libraries = pthread m dl\n";
    
    m_editor->SetText(exampleContent);
    ParsePropertiesToTree();
}

void SimplePropertyEditor::CreateControls()
{
    // 创建主分割窗口
    m_mainSplitter = new wxSplitterWindow(this, wxID_ANY, 
                                         wxDefaultPosition, wxDefaultSize,
                                         wxSP_3D | wxSP_LIVE_UPDATE);
    
    // 创建右侧分割窗口  
    m_rightSplitter = new wxSplitterWindow(m_mainSplitter, wxID_ANY,
                                          wxDefaultPosition, wxDefaultSize,
                                          wxSP_3D | wxSP_LIVE_UPDATE);
    
    // 创建三组件
    m_treeCtrl = new wxTreeCtrl(m_mainSplitter, wxID_ANY, 
                               wxDefaultPosition, wxDefaultSize,
                               wxTR_DEFAULT_STYLE | wxBORDER_SIMPLE);
    
    m_editor = new wxStyledTextCtrl(m_rightSplitter, wxID_ANY);
    m_propertyGrid = new wxPropertyGrid(m_rightSplitter, wxID_ANY);
    
    // 配置分割比例
    m_rightSplitter->SplitHorizontally(m_editor, m_propertyGrid, -200);
    m_mainSplitter->SplitVertically(m_treeCtrl, m_rightSplitter, 200);
    
    // 设置布局
    wxSizer* sizer = new wxBoxSizer(wxVERTICAL);
    sizer->Add(m_mainSplitter, 1, wxEXPAND);
    SetSizer(sizer);
    
    // 初始分割比例
    m_mainSplitter->SetSashPosition(300);
    m_rightSplitter->SetSashPosition(300);
}

void SimplePropertyEditor::SetupPropertyLexer()
{
    // 使用属性文件词法分析器
    m_editor->SetLexer(wxSTC_LEX_PROPERTIES);
    
    // 基本样式配置
    m_editor->StyleSetForeground(wxSTC_PROPS_DEFAULT, wxColour(0, 0, 0));
    m_editor->StyleSetForeground(wxSTC_PROPS_COMMENT, wxColour(0, 128, 0));
    m_editor->StyleSetForeground(wxSTC_PROPS_SECTION, wxColour(128, 0, 128));
    m_editor->StyleSetForeground(wxSTC_PROPS_KEY, wxColour(0, 0, 255));
    m_editor->StyleSetForeground(wxSTC_PROPS_ASSIGNMENT, wxColour(128, 128, 128));
    m_editor->StyleSetForeground(wxSTC_PROPS_DEFVAL, wxColour(255, 0, 0));
}

void SimplePropertyEditor::ParsePropertiesToTree()
{
    m_treeCtrl->DeleteAllItems();
    m_treeItemData.clear();
    
    wxTreeItemId root = m_treeCtrl->AddRoot("Properties");
    wxString content = m_editor->GetText();
    wxArrayString lines = wxStringTokenize(content, "\n", wxTOKEN_RET_EMPTY_ALL);
    
    wxTreeItemId currentSection;
    wxString currentSectionName;
    
    for (size_t i = 0; i < lines.GetCount(); i++) {
        wxString line = lines[i];
        wxString trimmed = line.Trim();  // 修复：使用临时变量
        
        if (trimmed.StartsWith("#")) {
            // 注释
            wxTreeItemId commentItem = m_treeCtrl->AppendItem(root, 
                wxString::Format("Comment: %s", trimmed.Left(20)));
            m_treeItemData[commentItem] = trimmed;
        }
        else if (trimmed.StartsWith("[") && trimmed.EndsWith("]")) {
            // 节
            currentSectionName = trimmed.Mid(1, trimmed.Length() - 2);
            currentSection = m_treeCtrl->AppendItem(root, currentSectionName);
            m_treeItemData[currentSection] = trimmed;
        }
        else if (trimmed.Contains("=")) {
            // 键值对
            int eqPos = trimmed.Find('=');
            wxString key = trimmed.Left(eqPos).Trim();
            wxString value = trimmed.Mid(eqPos + 1).Trim();
            
            wxTreeItemId parent = currentSection.IsOk() ? currentSection : root;
            wxTreeItemId kvItem = m_treeCtrl->AppendItem(parent, 
                wxString::Format("%s = %s", key, value));
            m_treeItemData[kvItem] = trimmed;
        }
    }
    
    m_treeCtrl->Expand(root);
}

void SimplePropertyEditor::UpdatePropertyGrid()
{
    m_propertyGrid->Clear();
    
    wxTreeItemId selection = m_treeCtrl->GetSelection();
    if (!selection.IsOk()) return;
    
    if (m_treeItemData.find(selection) == m_treeItemData.end()) return;
    
    wxString data = m_treeItemData[selection];
    
    if (data.StartsWith("[")) {
        // 节 - 显示名称
        m_propertyGrid->Append(new wxStringProperty("Section", "section", 
            data.Mid(1, data.Length() - 2)));
    }
    else if (data.Contains("=")) {
        // 键值对 - 可编辑
        int eqPos = data.Find('=');
        wxString key = data.Left(eqPos).Trim();
        wxString value = data.Mid(eqPos + 1).Trim();
        
        m_propertyGrid->Append(new wxStringProperty("Key", "key", key));
        m_propertyGrid->Append(new wxStringProperty("Value", "value", value));
    }
    else {
        // 注释或其他
        m_propertyGrid->Append(new wxStringProperty("Content", "content", data));
    }
}

void SimplePropertyEditor::GeneratePropertiesFromTree()
{
    // 简化版本：重新从编辑器解析
    ParsePropertiesToTree();
}

// 事件处理
void SimplePropertyEditor::OnTreeSelectionChanged(wxTreeEvent& event)
{
    UpdatePropertyGrid();
    event.Skip();
}

void SimplePropertyEditor::OnPropertyChanged(wxPropertyGridEvent& event)
{
    // 属性修改时更新数据模型
    wxString propName = event.GetPropertyName();
    wxVariant value = event.GetPropertyValue();
    
    event.Skip();
}

void SimplePropertyEditor::OnEditorModified(wxStyledTextEvent& event)
{
    // 编辑器内容改变时重新解析
    ParsePropertiesToTree();
    event.Skip();
}
